import React, { Component, Fragment } from "react";
// antd
import { Modal, Table, Button, Col, Pagination, Form, Input, message, Tag, Radio, Select } from "antd";
import Action from "@c/buttonAction/Index";
// http
import http from '../../utils/request';

const { TextArea } = Input;
const { Option } = Select;


function ListItem(props) {
    return <span><Tag style={{ marginTop: "5px"}} color="geekblue" >{props.value}</Tag></span>
}

class Faq extends Component {
    constructor(props){
        super(props);
        this.state = {
            // 表格分页
            total: '',
            page: 1,
            page_number: 10,
            dataSource: [],
            columns: [
                {title: "关键字", dataIndex: "keyword", key: "keyword", width: "400px",
                    render: (text, rowData) => {
                        const keyword = rowData.keyword.split(',')
                        const listItems = keyword.map((item) => 
                                <ListItem key={item.toString()} value={item} />
                        );
                        return (
                            <ul>{listItems}</ul>
                        )
                    }
                },
                {title: "消息类型", dataIndex: "answer_type", key: "answer_type", width: "150px"},
                {title: "回答", dataIndex: "answer", key: "answer", ellipsis: true},
                {title: "分类", dataIndex: "type", key: "type", width: "150px"},
                {title: "创建人", dataIndex: "creator", key: "creator", width: "150px"},
                {title: "操作", dataIndex: "operation", key: "operation", 
                    render: (text, rowData) => {
                        return (
                            <div className="inline-button">
                                <Action>
                                    <Action.Button onClick={() => this.onEditFaqBtn({rowData: rowData, status: true})}>编辑</Action.Button>
                                    <Action.Button onClick={() => this.onDeleteFaqBtn(rowData)}>删除</Action.Button>
                                </Action>
                            </div>
                        )
                    }           
                }
            ],
            loading: false,
            search_faq_keyword: null,
            search_faq_answer: null,
            search_faq_type: null,
            visible_add: false,     // 添加
            visible_edit: false,    // 编辑
            visible_delete: false,  // 删除
            faq_id: '',
            visible_edit_id: '',
            visible_edit_name: '',
            visable_edit_code: '',
            search_option_robot_type: [],

        }
        this.formRefAdd = React.createRef();
        this.formRefEdit = React.createRef();
        this.formRefMsg = React.createRef();
    }

    componentDidMount() {
        this.loadData()
        this.loadDataFaqType()
    }

    loadDataFaqType = () => {
        const requestData = {
            'page': 1,
            'limit': 1000,
        }
        http.get('/robot/faq/type', {params: requestData}).then(response=>{
            const search_option_robot_type = []
            const resp_data = response.data.data.items
            for (let i = 0; i < resp_data.length; i++) {
                search_option_robot_type.push(<Option key={resp_data[i].type}>{resp_data[i].type}</Option>)
            }
            this.setState({
                search_option_robot_type: search_option_robot_type
            })
        })
    }

    loadData = () => {
        this.setState({
            loading: true
        })
        console.log('page: ', this.state.page, 'page_number: ', this.state.page_number)
        const requestData = {
            'page': this.state.page,
            'limit': this.state.page_number,
            'keyword__contains': this.state.search_faq_keyword,
            'answer__contains': this.state.search_faq_answer,
            'type': this.state.search_faq_type,
        }

        // 获取分组列表
        http.get('/robot/faq', {params: requestData}).then(response=>{
            this.setState({
                dataSource: response.data.data.items,
                total: response.data.data.pages.total,
                loading: false
            })
        }).catch()
    }

    /** 切换每页数量 */
    onChangeSizePage = (page, page_number) => {
        this.setState({
            page: page,
            page_number: page_number,
        }, () => {
            this.loadData()
        })
    }    

    /** 搜索 */
    onFinishSearch = (data) => {
        this.setState({
            search_faq_type: data.type ? data.type : null,
            search_faq_keyword: data.keyword ? data.keyword : null,
            search_faq_answer: data.answer ? data.answer : null,
            page: 1,
        })
        this.loadData()
    }

    /** 添加按钮 */
    onAddFaqBtn = () => {
        this.setState({
            visible_add: true
        })
    }

    /** 添加取消 */
    onFinishAddCancel = () => {
        this.setState({
            visible_add: false
        })
        this.formRefAdd.current.resetFields()
    }

    /** 添加提交 */
    onFinishAdd = (data) => {
        const requestData = {
            keyword: data.keyword ? data.keyword : null,
            answer: data.answer ? data.answer : null,
            answer_type: data.answer_type ? data.answer_type : null,
            type: data.type ? data.type : null,
        }
        http.post('/robot/faq', requestData).then(response=>{
            message.success(response.data.msg)
            this.setState({
                visible_add: false,
            })
            this.formRefAdd.current.resetFields()
            this.loadData()
        }).catch()
    }

    /** 编辑按钮 */
    onEditFaqBtn = (data) => {
        http.get('/robot/faq').then(response=>{
            this.formRefEdit.current.setFieldsValue({
                id: data.rowData.id,
                answer: data.rowData.answer,
                answer_type: data.rowData.answer_type,
                keyword: data.rowData.keyword,
                type: data.rowData.type,
            })
        }).catch()
 
        this.setState({
            visible_edit: true,
        })
    }

    /** 编辑业务线取消 */
    onFinishEditCancel = () => {
        this.setState({
            visible_edit: false,

        })
        this.formRefEdit.current.resetFields();
    }

    /** 编辑业务线提交 */
    onFinishEdit = (data) => {
        const requestData = {
            keyword: data.keyword ? data.keyword : null,
            answer: data.answer ? data.answer : null,
            answer_type: data.answer_type ? data.answer_type: null,
            type: data.type ? data.type : null,
        }
        http.put('/robot/faq/' + data.id, requestData).then(response=>{
            message.success(response.data.msg)
            this.setState({
                visible_edit: false
            })
            this.formRefEdit.current.resetFields();
            this.loadData()
        }).catch()
    }

    /** 删除中间件类型提交 */
    handleFaqDelete = () => {
        http.delete('/robot/faq/' + this.state.faq_id).then(response=>{
            message.success(response.data.msg)
            this.setState({
                visible_delete: false,
                page: 1,
            })
            this.loadData()
        }).catch()    
    }

    /** 删除按钮 */
    onDeleteFaqBtn = (data) => {
        this.setState({
            faq_id: data.id,
            visible_delete: true
        })
    }

    // // 搜索业务线
    // onChangeRobotType = (value) => {
    //     this.setState({
    //         search_robot_type: value ? value : null
    //     })
    // }

    render(){
        const { loading, dataSource, columns, page, total, visible_add, visible_edit, visible_delete, search_option_robot_type } = this.state
        const rowSelection = {
            onChange: this.onCheckbox
        }
        var myStyle = {margin: '20px'}
        var myStyle1 = {margin: '10px', float: 'right'}
        return (
            <Fragment>
                <Form layout="inline" onFinish={this.onFinishSearch}>
                    <Form.Item label="关键字" name="keyword">
                        <Input placeholder="请输入关键字"  />
                    </Form.Item>

                    <Form.Item label="回答" name="answer">
                        <Input placeholder="请输入回答内容"  />
                    </Form.Item>

                    <Form.Item label="分类" name="type">
                        <Select
                            allowClear
                            showSearch
                            style={{ width: 200 }}
                            placeholder="请选择分类"
                            optionFilterProp="children"
                            // onChange={this.onChangeRobotType}
                            filterOption={(input, option) =>
                            option.children.toLowerCase().indexOf(input.toLowerCase()) >= 0
                            }
                        >
                            {search_option_robot_type}
                        </Select>
                    </Form.Item>   

                    <Form.Item shouldUpdate={true}>
                        <Button type="primary" htmlType="submit">搜索</Button>
                    </Form.Item>
                </Form>
                
                <div style={myStyle1}><Button type="primary" onClick={this.onAddFaqBtn}>添加问答</Button></div>
                <Table
                    pagination={false} 
                    rowSelection={rowSelection} 
                    rowKey="id" 
                    columns={columns} 
                    dataSource={dataSource}
                    loading={loading}
                    scroll={{ y: 500, x: '70vw' }}
                >
                </Table>

                <div style={myStyle}>
                    <Col span={16}>
                        <Pagination
                            onChange={this.onChangeSizePage}
                            current={page}
                            total={total}
                            showSizeChanger
                            showQuickJumper
                            showTotal={total => `Total ${total} items`}
                        />
                    </Col>
                </div>

                <Modal
                    title="添加问答"
                    visible={visible_add}
                    onCancel={this.onFinishAddCancel}
                    okText="确认"
                    cancelText="取消"
                    footer={null}
                    width="800px"
                >
                    <Form
                        onFinish={this.onFinishAdd}
                        ref={this.formRefAdd}
                        labelCol={{ span: 3 }}
                        wrapperCol={{ span: 20 }}
                    >
                        <Form.Item label="关键字" name="keyword" rules={[{ required: true}]}>
                            <Input placeholder="多个关键字以,分隔"></Input>
                        </Form.Item>

                        <Form.Item label="分类" name="type" rules={[{ required: true}]}>
                            <Select
                                allowClear
                                showSearch
                                style={{ width: '100%' }}
                                placeholder="选择问题分类"
                                // onChange={this.onChangePlatform}
                                >
                                {search_option_robot_type}
                            </Select>
                        </Form.Item>

                        <Form.Item label="消息类型" name="answer_type" rules={[{ required: true}]}>
                            <Radio.Group>
                                <Radio value="text">文本</Radio>
                                <Radio value="markdown">markdown</Radio>
                                <Radio value="link">链接</Radio>
                                <Radio value="img">图片</Radio>
                                <Radio value="action_card">卡片</Radio>
                                <Radio value="interactive_card">互动卡片</Radio>
                            </Radio.Group>
                        </Form.Item>

                        <Form.Item label="消息内容" name="answer" rules={[{ required: true}]}>
                            <TextArea autoSize={true} showCount />
                        </Form.Item>

                        <Form.Item>
                            <Button htmlType="submit" type="primary">确定</Button>
                        </Form.Item>                                                               
                    </Form>           
                </Modal>

                <Modal
                    title="编辑中间件"
                    visible={visible_edit}
                    onCancel={this.onFinishEditCancel}
                    okText="确认"
                    cancelText="取消"
                    footer={null}
                    width="800px"
                >
                    <Form
                        onFinish={this.onFinishEdit}
                        ref={this.formRefEdit}
                        labelCol={{ span: 3 }}
                        wrapperCol={{ span: 20 }}
                    >
                        <Form.Item label="ID" name="id" hidden>
                            <Input ></Input>
                        </Form.Item>
                        <Form.Item label="关键字" name="keyword" rules={[{ required: true}]}>
                            <Input placeholder="多个关键字以,分隔"></Input>
                        </Form.Item>

                        <Form.Item label="分类" name="type" rules={[{ required: true}]}>
                            <Select
                                allowClear
                                showSearch
                                style={{ width: '100%' }}
                                placeholder="选择问题分类"
                                // onChange={this.onChangePlatform}
                                >
                                {search_option_robot_type}
                            </Select>
                        </Form.Item>

                        <Form.Item label="消息类型" name="answer_type" rules={[{ required: true}]}>
                            <Radio.Group>
                                <Radio value="text">文本</Radio>
                                <Radio value="markdown">markdown</Radio>
                                <Radio value="link">链接</Radio>
                                <Radio value="img">图片</Radio>
                                <Radio value="action_card">卡片</Radio>
                                <Radio value="interactive_card">互动卡片</Radio>
                            </Radio.Group>
                        </Form.Item>

                        <Form.Item label="消息内容" name="answer" rules={[{ required: true}]}>
                            <TextArea autoSize={true} showCount />
                        </Form.Item>

                        <Form.Item>
                            <Button htmlType="submit" type="primary">确定</Button>
                        </Form.Item>                                                               
                    </Form>           
                </Modal>

                <Modal
                    title="删除类型"
                    visible={visible_delete}
                    onOk={this.handleFaqDelete}
                    onCancel={() => {this.setState({visible_delete: false, faq_id: ''})}}
                    okText="确认"
                    cancelText="取消"
                >
                    <p>确定<span style={{color: 'red'}}>删除</span>? 删除后将无法恢复</p>
                </Modal>
            </Fragment>
        )
    }
}
export default Faq;